<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <h2>个人信息</h2>
            </div>
          </template>
          
          <div class="profile-info">
            <el-avatar :size="100" class="avatar">
              {{ customerStore.currentCustomer?.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <h3>{{ customerStore.currentCustomer?.username }}</h3>
            <p class="user-role">普通用户</p>
          </div>

          <el-divider />

          <div class="info-list">
            <div class="info-item">
              <el-icon><phone /></el-icon>
              <span>{{ customerStore.currentCustomer?.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <el-icon><message /></el-icon>
              <span>{{ customerStore.currentCustomer?.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <el-icon><location /></el-icon>
              <span>{{ customerStore.currentCustomer?.address || '未设置' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <h2>修改信息</h2>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            @submit.prevent
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>

            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>

            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入电子邮箱" />
            </el-form-item>

            <el-form-item label="收货地址" prop="address">
              <el-input
                v-model="form.address"
                type="textarea"
                :rows="3"
                placeholder="请输入详细收货地址"
              />
            </el-form-item>

            <el-form-item label="修改密码">
              <el-button link @click="showPasswordDialog = true">
                点击修改密码
              </el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSubmit">
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordChange">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useCustomerStore } from '@/stores/customerStore'
import { Phone, Message, Location } from '@element-plus/icons-vue'

const customerStore = useCustomerStore()
const formRef = ref(null)
const passwordFormRef = ref(null)
const showPasswordDialog = ref(false)

const form = ref({
  username: '',
  phone: '',
  email: '',
  address: ''
})

const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (passwordForm.value.confirmPassword !== '') {
      passwordFormRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, message: '地址长度不能小于5个字符', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 更新用户信息
    await customerStore.updateProfile({
      phone: form.value.phone,
      email: form.value.email,
      address: form.value.address
    })
    
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    ElMessage.error(error.message || '更新失败，请重试')
  }
}

const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    
    // 验证当前密码
    if (passwordForm.value.currentPassword !== customerStore.currentCustomer?.password) {
      ElMessage.error('当前密码错误')
      return
    }
    
    // 更新密码
    await customerStore.updatePassword(passwordForm.value.newPassword)
    
    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    ElMessage.error(error.message || '密码修改失败，请重试')
  }
}

onMounted(() => {
  // 初始化表单数据
  const customer = customerStore.currentCustomer
  if (customer) {
    form.value = {
      username: customer.username,
      phone: customer.phone || '',
      email: customer.email || '',
      address: customer.address || ''
    }
  }
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
}

.profile-info {
  text-align: center;
  padding: 20px 0;
}

.avatar {
  background-color: #409eff;
  color: #fff;
  font-size: 40px;
  margin-bottom: 16px;
}

.profile-info h3 {
  margin: 10px 0 5px;
  font-size: 18px;
}

.user-role {
  color: #909399;
  margin: 0;
}

.info-list {
  margin-top: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #606266;
}

.info-item .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.info-item:last-child {
  margin-bottom: 0;
}
</style> 